package de.koller.worlders.render;

import de.koller.oceanFramework.gl.util.FrameTexture;
import de.koller.oceanFramework.gl.util.ViewUtil;
import de.koller.worlders.WSea;
import de.koller.worlders.WorldersRoot;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

public class ViewportGL extends WSea {
	
	//Warning slow!
	private boolean renderOnTexture = false;
	
	private FrameTexture screen;

	@Override
	protected void init() {
		super.init();

		initFrameOrtho();
		screen = FrameTexture.generate( 1024, 1024 );
	}

	private void initFrameOrtho() {
		GL11.glMatrixMode( GL11.GL_PROJECTION );
		GL11.glLoadIdentity();

		GL11.glOrtho( 0, Display.getWidth(), Display.getHeight(), 0, -1000, 1000 );
		
		GL11.glMatrixMode( GL11.GL_MODELVIEW );
		GL11.glLoadIdentity();
	}
	
	private void initOrtho() {
		GL11.glMatrixMode( GL11.GL_PROJECTION );
		GL11.glLoadIdentity();

		GL11.glOrtho( 0, WorldersRoot.D_WIDTH, WorldersRoot.D_HEIGHT, 0, -1000, 1000 );
		
		GL11.glMatrixMode( GL11.GL_MODELVIEW );
		GL11.glLoadIdentity();
	}
	
	public void bind() {
		if( renderOnTexture )
			screen.bindFBO();
		initOrtho();
		
		GL11.glEnable( GL11.GL_CULL_FACE );
		GL11.glCullFace( GL11.GL_BACK );

		GL11.glDepthFunc( GL11.GL_LEQUAL );
		
		GL11.glAlphaFunc( GL11.GL_GREATER, 0.1f );
		GL11.glEnable( GL11.GL_ALPHA_TEST );
	}
	
	public void rebind() {
		if( renderOnTexture )
			screen.bindFBOWithoutClear();
	}
	
	public void unbind() {
		if( renderOnTexture )
			screen.unbindFBO();
	}
	
	public void renderFrame() {
		if( !renderOnTexture )
			return;
		
		initFrameOrtho();
		
		screen.bindTexture();
		
		ViewUtil.draw2D( 0, 0, WorldersRoot.D_WIDTH, WorldersRoot.D_HEIGHT, 0, 0, 1, 1, 0 );
	}
	
}
